package com.tianci.appstore.ui.list.move;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.coocaa.x.framework.utils.PMUtils.PackageMoveLocation;
import com.tianci.appstore.R;
import com.tianci.appstore.controller.manager.MoveManagerController;
import com.tianci.appstore.ui.SkinManager;
import com.tianci.appstore.ui.data.SkyListAppData;
import com.tianci.appstore.ui.data.SkyListAppData.ListType;
import com.tianci.appstore.ui.dialog.ConfirmProcessDialog;
import com.tianci.appstore.ui.list.ListBlock;
import com.tianci.appstore.ui.list.manage.ManageBaseListView;
import com.tianci.appstore.ui.list.manage.ManageListController.OnNeedSizeChangeListener;
import com.tianci.appstore.ui.list.manage.MultiSelectUIListener;
import com.tianci.appstore.ui.util.UICommon;
import com.tianci.appstore.ui.widget.OnButtonClickListener;
import com.tianci.appstore.ui.widget.SkyCustomLayout;
import com.tianci.appstore.ui.widget.TipToast;
import com.tianci.appstore.utils.SkyConstants;

import java.util.List;

public class MoveListView extends ManageBaseListView implements
        MultiSelectUIListener, OnClickListener, OnButtonClickListener, OnMoveStateChangeListener, OnNeedSizeChangeListener {
    private LinearLayout btnLayout;
    //private Button selectButton;
    //private Button cancelButton;
    private Button moveAllButton;
    private boolean inSelectMode = false;
    private TextView countSizeText;
    private PackageMoveLocation mLocation = null;

    private static final int UPDATE_COUNT = 10;
    private static final int SELECT_BTN_ID = 101;
    private static final int CANCEL_BTN_ID = 102;
    private static final int MOVEALL_BTN_ID = 103;

    private LinearLayout.LayoutParams btnParams;

    private boolean firstDataLoaded = false;

    public MoveListView(Context context, PackageMoveLocation location) {
        super(context, ListType.MOVE_APP_LIST);
        // TODO Auto-generated constructor stub
        this.mLocation = location;
        mController.setMultiSelectUIListener(this);
        mController.setNeedSizeChangeListener(this);
        setLoadingVisible(true);
        initTopRightLayout();
        refreshListData(MoveManagerController.getInstance(mContext).getListAppDatas(location));
        MoveManagerController.getInstance(mContext).setMoveStateChangeListener(this);
    }

    private void initTopRightLayout() {
        LinearLayout rightTopLayout = new LinearLayout(mContext);
        rightTopLayout.setGravity(Gravity.RIGHT | Gravity.CENTER_VERTICAL);

        countSizeText = UICommon.newTextView(mContext, rightTopTextSize, R.color.btnColor);
        countSizeText.setPadding(SkyConstants.Div(20), 0, SkyConstants.Div(20), 0);
        rightTopLayout.addView(countSizeText);

        FrameLayout layout = new FrameLayout(mContext);
//        ImageView btnTopImage = new ImageView(mContext);
//        SkinManager.setBackground(btnTopImage, R.drawable.pic_line);
//        LayoutParams dividerParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, Gravity.TOP);
//        layout.addView(btnTopImage, dividerParams);

        btnLayout = new LinearLayout(mContext);
        btnLayout.setPadding(SkyConstants.Div(22), 0, SkyConstants.Div(22), 0);
        layout.addView(btnLayout, new LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
        rightTopLayout.addView(layout);
        btnParams = new LinearLayout.LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        btnParams.weight = 1;
        //selectButton = newButton(SELECT_BTN_ID, R.string.select);
        //btnLayout.addView(selectButton, btnParams);

        //cancelButton = newButton(CANCEL_BTN_ID, R.string.cancel);
        switch (mLocation) {
            case EXTERNAL_MEDIA:
                moveAllButton = newButton(MOVEALL_BTN_ID, R.string.move_to_inter);
                break;
            case INTERNAL_MEMORY:
                moveAllButton = newButton(MOVEALL_BTN_ID, R.string.move_to_sdcard);
                break;
            default:
                break;
        }
        btnLayout.addView(moveAllButton, btnParams);
        LayoutParams topRightParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, Gravity.TOP | Gravity.RIGHT);
        topRightParams.setMargins(0, SkyConstants.Div(85), SkyConstants.Div(75), 0);
        this.addView(rightTopLayout, topRightParams);
    }

    private Button newButton(int btnId, int strId) {
        Button btn = UICommon.newButton(mContext, rightTopTextSize, R.color.btnColor);
        SkinManager.setBackground(btn, R.drawable.search_selector);
        //btn.setPadding(SkyConstants.Div(27), 0, SkyConstants.Div(27), SkyConstants.Div(6));
        btn.setText(strId);
        btn.setId(btnId);
        btn.setOnClickListener(this);
        return btn;
    }

    private Handler mainHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case UPDATE_LIST:
                    refreshListData((List<SkyListAppData>) msg.obj);
                    break;
                case UPDATE_COUNT:
                    refreshCountAndSize(msg.arg1, msg.getData().getFloat("appSize"), msg.getData().getFloat("freeSize"));
                    break;
                case DELAY_DISSMISS_DIALOG:
                    dialog.dismiss();
                    break;
                case UPDATE_SUCCESS_STATE:
                    dialog.enterResultState(getResources().getString(R.string.move_complete));
                    setBtnEnabled(moveAllButton, false);
                    break;
                case UPDATE_FAILED_STATE:
                    dialog.enterFailedState((List<SkyListAppData>) msg.obj, "转移失败了");
                    break;
            }
            super.handleMessage(msg);
        }
    };


    private void refreshCountAndSize(int appCount, float appSize, float freeSize) {
        if (appCount == 0) {
            setEmptyTipVisible(true, mContext.getResources().getString(R.string.no_app_to_move));
            setBtnEnabled(moveAllButton, false);
        } else {
            setEmptyTipVisible(false, null);
        }
        String str = mContext.getResources().getString(R.string.app_count_str);
        countSizeText.setText(String.format("%d%s %.1fMB/%.1fMB", appCount, str, appSize, freeSize));
    }

    private void refreshListData(List<SkyListAppData> dataList) {
        if (dataList == null || dataList.size() == 0) {
            setEmptyTipVisible(true, mContext.getResources().getString(R.string.no_app_to_move));
            return;
        }
        setLoadingVisible(false);
        setEmptyTipVisible(false, null);
        try {
            mController.setDataList(dataList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        setSelectMode(true);

        if (!firstDataLoaded) {
            String moveToStr;
            if (mLocation == PackageMoveLocation.EXTERNAL_MEDIA)
                moveToStr = mContext.getResources().getString(R.string.internal_disk);
            else
                moveToStr = mContext.getResources().getString(R.string.sdcard);
            String tipStr = String.format(mContext.getResources().getString(R.string.move_select_tip), moveToStr);
            TipToast.getInstance(mContext).showToast(
                    SkinManager.getResDrawable(R.drawable.toast_icon_tip), tipStr, 3500, Gravity.CENTER);
            setBtnEnabled(moveAllButton, false);
            firstDataLoaded = true;
        }
        resetFocus();
    }

    private void setSelectMode(boolean selMode) {
        if (this.inSelectMode == selMode)
            return;
        this.inSelectMode = selMode;
        if (selMode) {
            //btnLayout.removeAllViews();
            //btnLayoq gut.addView(cancelButton, btnParams);
            //btnLayout.addView(moveAllButton, btnParams);
            //setBtnEnabled(moveAllButton, false);

//            ListBlock.setSelectMode(inSelectMode);
            setInSelectMode(inSelectMode);
            for (int i = 0; i < listFlipper.getChildCount(); i++) {
                SkyCustomLayout child = (SkyCustomLayout) listFlipper.getChildAt(i);
                for (int j = 0; j < child.getChildCount(); j++) {
                    ListBlock block = (ListBlock) child.getChildAt(j);
                    block.refreshSelectState();
                }
            }
            mController.clearSelectedDataList();
            resetFocus();
        } else {
            //btnLayout.removeAllViews();
            //btnLayout.addView(selectButton, btnParams);
            mController.clearSelectedDataList();
//            ListBlock.setSelectMode(false);
            setInSelectMode(false);
            for (int i = 0; i < listFlipper.getChildCount(); i++) {
                SkyCustomLayout child = (SkyCustomLayout) listFlipper.getChildAt(i);
                for (int j = 0; j < child.getChildCount(); j++) {
                    ListBlock block = (ListBlock) child.getChildAt(j);
                    block.refreshSelectState();
                }
            }
            resetFocus();
        }
    }

    @Override
    public void OnSelectCountChanged(int count) {
        // TODO Auto-generated method stub
        if (inSelectMode) {
            setBtnEnabled(moveAllButton, count != 0);

        }
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
            case SELECT_BTN_ID:
                if (!inSelectMode)
                    setSelectMode(!inSelectMode);
                break;
            case CANCEL_BTN_ID:
                if (inSelectMode) {
                    setSelectMode(!inSelectMode);
                    resetFocus();
                }
                break;
            case MOVEALL_BTN_ID:
                if (mController.getSelectedDataList().size() == 0) {
                    return;
                }
                if (dialog == null) {
                    dialog = new ConfirmProcessDialog(mContext);
//                    ColorButton btn = new ColorButton(mContext, R.string.cancel, R.drawable.btn_gray, R.drawable.btn_gray_focus);
//                    dialog.addButton(btn, 0, false);
//                    ColorButton btn2 = new ColorButton(mContext, R.string.move, R.drawable.btn_green, R.drawable.btn_green_focus);
//                    dialog.addButton(btn2, 1, true);
//                    dialog.setButtonClickListener(this);
                } else {
                    dialog.initStatus();
                }
                //String contentStr = "";
                if (mController.getSelectedDataList().size() == 1) {
                    dialog.setIconTitle(mController.getSelectedDataList().get(0), mController.getSelectedDataList().get(0).getTitle());
//                    contentStr = String.format(getResources().getString(R.string.confirm_move_app),
//                            mController.getSelectedDataList().get(0).getTitle());
                } else {
                    dialog.setIconTitle(SkinManager.getResDrawable(R.drawable.icon_sdcard), getResources().getString(R.string.move_app));
//                    contentStr = getResources().getString(R.string.select_move_size) + mController.getSelectedDataList().size();
                }
//                dialog.setContent(contentStr);
                MoveManagerController.getInstance(mContext).moveAppList(mController.getSelectedDataList(), mLocation);
                mController.clearSelectedDataList();
                dialog.enterWaitState(getResources().getString(R.string.moving));
                dialog.show();
                //setSelectMode(false);
                break;
        }
    }

    @Override
    public void destroyController() {
        // TODO Auto-generated method stub
        MoveManagerController.getInstance(mContext).destroy();
        if (dialog != null) {
            dialog.onDestory();
        }
        super.destroyController();
    }

    @Override
    public boolean processKeyDown(int keyCode) {
        // TODO Auto-generated method stub
//        if(keyCode == KeyEvent.KEYCODE_BACK)
//        {
//            if(inSelectMode)
//            {
//                setSelectMode(!inSelectMode);
//                return true;
//            }
//        }
        return false;
    }

    private ConfirmProcessDialog dialog;
    private String dlgPkgName;
    private boolean silent = false;

    @Override
    public void onBlockClicked(View v, SkyListAppData data, int index) {
        // TODO Auto-generated method stub
//        dlgPkgName = data.getPkgName();
//        if (dialog == null)
//            dialog = new CommonAppOpDialog(mContext);
//        String contentStr = String.format(
//                mContext.getResources().getString(R.string.confirm_move_app), data.getTitle());
//        dialog.setData(data.getId(), data.getTitle(), contentStr, data.getIconUrl());
//        ColorButton btn = new ColorButton(mContext, R.string.cancel, R.drawable.btn_gray,
//                R.drawable.btn_gray_focus);
//        dialog.addButton(btn, 0, false);
//        ColorButton btn2 = new ColorButton(mContext, R.string.move, R.drawable.btn_green,
//                R.drawable.btn_green_focus);
//        dialog.addButton(btn2, 1, true);
//        dialog.show();
    }

    @Override
    public void onClick(int index) {
        // TODO Auto-generated method stub
        if (index == 0) {
            dialog.hide();
        } else if (index == 1) {
            MoveManagerController.getInstance(mContext).moveAppList(mController.getSelectedDataList(), mLocation);
            mController.clearSelectedDataList();
            dialog.enterWaitState(getResources().getString(R.string.moving));
        }
    }

    @Override
    public void refreshCountAndSpace(int appCount, float appSize, float freeSize,
                                     PackageMoveLocation location) {
        if (location.toString().equals(mLocation.toString())) {
            Message msg = mainHandler.obtainMessage(UPDATE_COUNT);
            msg.arg1 = appCount;
            Bundle bundle = new Bundle();
            bundle.putFloat("appSize", appSize);
            bundle.putFloat("freeSize", freeSize);
            msg.setData(bundle);
            mainHandler.sendMessage(msg);
        }
    }

    @Override
    public void refreshAppDatas(List<SkyListAppData> appDatas, PackageMoveLocation location) {
        if (location.toString().equals(mLocation.toString())) {
            Message msg = mainHandler.obtainMessage(UPDATE_LIST);
            msg.obj = appDatas;
            mainHandler.sendMessage(msg);
        }
    }

    @Override
    public void refreshResult(List<SkyListAppData> appDatas) {
        if (dialog != null && dialog.isShowing()) {
            if (appDatas.size() > 0) {
                Message msg = mainHandler.obtainMessage(UPDATE_FAILED_STATE);
                msg.obj = appDatas;
                mainHandler.sendMessage(msg);
                mController.clearSelectedDataList();
            } else {
                mainHandler.sendEmptyMessage(UPDATE_SUCCESS_STATE);
                mainHandler.sendEmptyMessageDelayed(DELAY_DISSMISS_DIALOG, 2000);
            }
        }
    }

    @Override
    public boolean needSizeChange(long needSize) {
        boolean flag = true;
        String content = "";
        switch (mLocation) {
            case EXTERNAL_MEDIA:
                if (needSize / SkyConstants.BTOM > MoveManagerController.getInstance(mContext).getAvailableInternalMemorySize() - 100) {
                    flag = false;
                    content = getResources().getString(R.string.no_native_space_can_not_move);
                }
                break;
            case INTERNAL_MEMORY:
                if (needSize / SkyConstants.BTOM > MoveManagerController.getInstance(mContext).getSDcardAvailableSpace() - 100) {
                    flag = false;
                    content = getResources().getString(R.string.no_sdcard_space_can_not_move);
                }
                break;
            default:
                break;
        }
        if (!flag) {
//            Toast.makeText(mContext, content, Toast.LENGTH_LONG).show();
            TipToast.getInstance(mContext).showTipToast(content);
        }
        return flag;
    }
}
